package com.xyzwps.server.paimon.app.filter

import com.xyzwps.server.paimon.app.ContextUser
import com.xyzwps.server.paimon.error.Errors
import com.xyzwps.server.paimon.model.entity.UserSession
import org.aspectj.lang.reflect.MethodSignature
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint

/**
 * @see AppFilterToken.AUTH
 * @see com.xyzwps.server.paimon.ui.GraphQlAuthInterceptor
 * @see com.xyzwps.server.paimon.ui.MvcAuthInterceptor
 */
class TokenAuth {

    companion object {
        fun check(p: MethodInvocationProceedingJoinPoint) {
            val signature = p.signature
            if (signature is MethodSignature) {
                val argumentTypes = signature.parameterTypes
                val argumentNames = signature.parameterNames
                val args = p.args
                for (i in argumentTypes.indices) {
                    val t = argumentTypes[i]
                    val n = argumentNames[i]
                    val v = args[i]
                    if ((t == String::class.java && n == "token")
                        || t == ContextUser::class.java
                        || t == UserSession::class.java
                    ) {
                        if (v == null) {
                            throw Errors.UNAUTHENTICATED.toEx()
                        }
                    }
                }
            } else {
                throw IllegalArgumentException("Unsupported signature type: ${signature.javaClass.name}")
            }
        }
    }
}
